package nz.ac.massey.webtech.servlets.header;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

/**
 * Servlet displaying the request headers.
 * @author  Jens Dietrich   
 * @version 1.0
 */
public class HeaderAnalyzerServlet extends HttpServlet {
    
    /** Initializes the servlet.
     */
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        
    }
    
    /** Destroys the servlet.
     */
    public void destroy() {
        
    }
    
    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
       
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet</title>");
        out.println("</head>");
        out.println("<body>");
         
        out.println("<h1>Request Headers</h1>");
        out.println("<table border><th>Header Name</th><th>Header Value</th>");
        // list headers send by the client
        for (Enumeration headers = request.getHeaderNames();headers.hasMoreElements();) {
            String header = headers.nextElement().toString();
            String value = request.getHeader(header);
            out.print("<tr><td>");
            out.print(header);
            out.print("</td><td>");
            out.print(value);
            out.println("</td></tr>");
        }
        
        out.println("</table>");
        out.println("</body>");
        out.println("</html>");
        
        out.close();
    }
    
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
    
}
